package com.runchamp;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/*
Adaps current stats items to list.
 */
public class JSONAdapterStatsList extends BaseAdapter {

    Context mContext;
    LayoutInflater mInflater;
    JSONArray mJsonArray;

    public JSONAdapterStatsList(Context context, LayoutInflater inflater) {
        mContext = context;
        mInflater = inflater;
        mJsonArray = new JSONArray();
    }

    @Override
    public int getCount() {
        return mJsonArray.length();
    }

    @Override
    public Object getItem(int position) {
        return mJsonArray.optJSONObject(mJsonArray.length() - 1 - position);
    }

    @Override
    public long getItemId(int position) {
        JSONObject json = (JSONObject) getItem(position);
        try {
            long key = json.getLong("key");
            return key;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;

        // check if the view already exists
        // if so, no need to inflate and findViewById again!
        if (convertView == null) {

            // Inflate the custom row layout from your XML.
            convertView = mInflater.inflate(R.layout.row_stats, null);

            // create a new "Holder" with subviews
            holder = new ViewHolder();
            holder.distanceTextView = (TextView) convertView.findViewById(R.id.text_distance);
            holder.nameTextView = (TextView) convertView.findViewById(R.id.text_race_name);
            //  holder.speedTimeTextView = (TextView) convertView.findViewById(R.id.text_avg_speed);
            holder.positionTextView = (TextView) convertView.findViewById(R.id.text_position);
            holder.flags = (ImageView) convertView.findViewById(R.id.finished_flag);

            // hang onto this holder for future recyclage
            convertView.setTag(holder);
        } else {

            // skip all the expensive inflation/findViewById
            // and just get the holder you already made
            holder = (ViewHolder) convertView.getTag();
        }

        // Get the current race's data in JSON form
        JSONObject jsonObject = (JSONObject) getItem(position);

        // Grab the distance, time and manager from the JSON
        String distance = "";
        String name = "";
        String speed = "";


        if (jsonObject.has("actualdistance")) {
            distance = jsonObject.optString("actualdistance");
        }

        if (jsonObject.has("speed")) {
            speed = jsonObject.optString("speed");
        }


        if (jsonObject.has("name")) {
            name = jsonObject.optString("name");
        }

        // Send these Strings to the TextViews for display
        holder.distanceTextView.setText(String.valueOf(lessPrecision(Double.valueOf(distance))));
        holder.nameTextView.setText(name);
//     holder.speedTimeTextView.setText(String.valueOf(lessPrecision(Double.valueOf(speed))));


        holder.positionTextView.setText(String.valueOf(position + 1) + ".");

        try {


            if (jsonObject.has("status") && jsonObject.optString("status").equals("finished")) {


                holder.flags.setVisibility(View.VISIBLE);
            } else if (jsonObject.has("status") && jsonObject.optString("status").equals("gaveup")) {
                holder.flags.setImageResource(R.drawable.red_finish_flag);
                holder.flags.setVisibility(View.VISIBLE);
            } else {
                holder.flags.setVisibility(View.INVISIBLE);
            }

        } catch (Exception e) {
        }


        return convertView;
    }

    public void updateData(JSONArray jsonArray) {
        // update the adapter's dataset
        mJsonArray = reverse(jsonArray);
        notifyDataSetChanged();
    }

    public JSONArray reverse(JSONArray input) {
        try {
            JSONArray result = new JSONArray();
            for (int i = 0; i < input.length(); i++) {
                result.put(input.length() - i - 1, input.get(i));

            }
            return result;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return input;

    }

    double lessPrecision(Double num) {
        Double afterPoint = num - num.intValue();
        afterPoint *= 100;
        Integer temp = afterPoint.intValue();
        afterPoint = temp.doubleValue();
        afterPoint /= 100;

        return num.intValue() + afterPoint;
    }

    // this is used so you only ever have to do
    // inflation and finding by ID once ever per View
    private static class ViewHolder {
        public TextView distanceTextView;
        public TextView nameTextView;
        public TextView speedTimeTextView;
        public TextView positionTextView;
        public ImageView flags;

    }


}
